<template>
  <el-upload
    ref="upload"
    v-loading="loading"
    v-bind="$attrs"
    :action="config.action"
    :headers="config.headers"
    :on-error="handleError"
    :on-success="handleSuccess"
    :before-upload="handleBeforeUpload">
    <slot></slot>
    <slot name="tip" slot="tip"></slot>
  </el-upload>
</template>

<script>

import {checkImg, getInstance} from '../utils';
import {Validate} from 'js-utils/validate';
import {dataURLtoFile, fileToDataURL} from 'js-utils';
import ImgClip from '../img-clip';

export default {
  name: 'upload-box',
  props: {
    size: {
      type: Number,
      default: 5
    },
    uploadConfig: {
      type: Object
    },
    type: {
      type: String,
      default: 'jpeg|jpg|png'
    },
    onError: {
      type: Function
    },
    beforeUpload: {
      type: Function
    },
    onSuccess: {
      type: Function
    },
    clipSize: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      fileName: '',
      imgData: '',
      loading: false,
      config: this.uploadConfig || this.$getGlobalConfig('upload')
    };
  },
  methods: {
    instanceImgClip() {
      let options = {
        props: {
          width: {
            type: Number,
            default: this.clipSize[0]
          },
          height: {
            type: Number,
            default: this.clipSize[1]
          },
          img: {
            type: String,
            default: this.imgData
          }
        }
      };
      let instance = getInstance(ImgClip, options);
      instance.$on('submitClip', (dataURL) => {
        let file = dataURLtoFile(dataURL, this.fileName);
        this.$refs.upload.handleStart(file);
        this.$refs.upload.$refs['upload-inner'].post(file);
        this.loading = true;
      });
      instance.$on('update:showFlag', () => {
        instance.showFlag = false;
        setTimeout(_ => {
          document.body.removeChild(instance.$el);
          instance.$destroy();
          instance = null;
        }, 300);
      });
      instance.showFlag = true;
    },
    handleSuccess(e) {
      this.loading = false;
      if (this.onSuccess) {
        this.onSuccess(e);
      }
    },
    handleError(e) {
      this.$message.error('图片上传失败');
      this.loading = false;
      if (this.onError) {
        this.onError(e);
      }
    },
    handleBeforeUpload(file) {
      let valid = false;
      if (this.beforeUpload) {
        valid = this.beforeUpload(file, this.loading);
      } else {
        valid = checkImg(file, this.config.size || this.size, this.type);
      }
      if (!valid) return false;
      if (Validate.isEmpty(this.clipSize)) {
        this.loading = true;
        return true;
      } else {
        fileToDataURL(file).then(data => {
          this.fileName = file.name;
          this.imgData = data;
          this.instanceImgClip();
        });
        return false;
      }
    }
  },
  mounted() {
  }
};
</script>

<style>

</style>
